/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GuiBuscarUsuario.java
 *
 * Created on 26/11/2011, 14:40:47
 */
package view.gui;

import java.util.List;
import javax.swing.table.DefaultTableModel;
import model.dao.DaoUsuario;
import model.dominio.Usuario;

/**
 *
 * @author danielgr
 * Classe responsável por exibir interface gráfica para busca de Usuários do sistema.
 * Além de enviar a busca, retorna-o para outra interface, para que dados do Usuário sejam vistos e editados, se necessário.
 * 
 * @see GuiPrincipal
 * 
 */
public class GuiBuscarUsuario  extends JInternalFramePermissao {

    private List<Usuario> lista;

    /** Creates new form GuiBuscarUsuario */
    /**
     * Construtor da interface.
     * Inicialização dos componentes para exibição gráfica da busca por Usuário.
     */
    public GuiBuscarUsuario() {
        initComponents();

    }

    /**
     * Função responsável por efetuar a busca dos Usuários no banco de dados.
     * Busca pode ser realizada através do CPF, do Nome ou de ambos.
     * Exibição do resultado da busca na tabela, informando Nome, CPF e Login do Usuário.
     */
    public void buscarUsuarios() {
        Usuario u = new Usuario();
        if (!cpfUsuario.getText().equals("   .   .   -  ")) {
            u.setCpf(cpfUsuario.getText());
        } else if (!nomeUsuario.getText().isEmpty()) {
            u.setNome(nomeUsuario.getText());
        }
        lista = new DaoUsuario().buscarUsuarios(u);
        DefaultTableModel model = (DefaultTableModel) tabelaUsuario.getModel();

        model.setRowCount(0);
        String[] s = new String[4];
        for (Usuario usuario : lista) {
            s[0] = usuario.getNome();
            s[1] = usuario.getCpf();
            s[2] = usuario.getLogin();
            model.addRow(s);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        nomeUsuario = new javax.swing.JTextField();
        localizarUsuario = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        cpfUsuario = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaUsuario = new javax.swing.JTable();

        setClosable(true);
        setTitle("Buscar Usuário");
        getContentPane().setLayout(null);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros de busca"));
        jPanel1.setLayout(null);

        jLabel1.setText("Nome:");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(10, 30, 70, 30);

        nomeUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nomeUsuarioActionPerformed(evt);
            }
        });
        jPanel1.add(nomeUsuario);
        nomeUsuario.setBounds(80, 30, 200, 30);

        localizarUsuario.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/imagens/Search-icon.png"))); // NOI18N
        localizarUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                localizarUsuarioActionPerformed(evt);
            }
        });
        jPanel1.add(localizarUsuario);
        localizarUsuario.setBounds(510, 30, 40, 40);

        jLabel2.setText("CPF:");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(290, 30, 50, 30);

        try {
            cpfUsuario.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cpfUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cpfUsuarioActionPerformed(evt);
            }
        });
        jPanel1.add(cpfUsuario);
        cpfUsuario.setBounds(340, 30, 160, 30);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(0, 0, 560, 80);

        tabelaUsuario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "Nome", "CPF", "Login"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabelaUsuario.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabelaUsuario.getTableHeader().setReorderingAllowed(false);
        tabelaUsuario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaUsuarioMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaUsuario);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(0, 80, 560, 190);

        setBounds(0, 0, 571, 306);
    }// </editor-fold>//GEN-END:initComponents

   private void localizarUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_localizarUsuarioActionPerformed
       buscarUsuarios();
   }//GEN-LAST:event_localizarUsuarioActionPerformed

    /**
     * Ao efetuar um clique do mouse na tabela, esta é enviada para uma interface gráfica, +
     *	permitindo visualizar as informações do Usuário melhor ou editá-las, se necessário.
     * @param evt 
     */
   private void tabelaUsuarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaUsuarioMouseClicked
       if (evt.getClickCount() > 1) {
           int linha = tabelaUsuario.getSelectedRow();
           GuiPrincipal.addJanela(new GuiDadosUsuario(lista.get(linha)));
           this.dispose();
       }
   }//GEN-LAST:event_tabelaUsuarioMouseClicked

   private void nomeUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nomeUsuarioActionPerformed
       buscarUsuarios();
   }//GEN-LAST:event_nomeUsuarioActionPerformed

   private void cpfUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cpfUsuarioActionPerformed
       buscarUsuarios();
   }//GEN-LAST:event_cpfUsuarioActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField cpfUsuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton localizarUsuario;
    private javax.swing.JTextField nomeUsuario;
    private javax.swing.JTable tabelaUsuario;
    // End of variables declaration//GEN-END:variables

    @Override
    public int getPermissao() {
        return 5;
    }
}
